import { outData } from './index.js';
let data = []
let allData = []
let theRequest = {};
let data_list = {}


// 在页面加载时获取数据
window.onload = async function () {
    try {
        // 使用 async/await 获取数据
        const response = await fetch('../data/data.json');
        allData = await response.json();

        // 获取 URL 参数并处理数据
        let url = location.search;
        if (url.indexOf("?") != -1) {
            let str = url.substr(1);
            let strs = str.split("&");
            for (let i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
            }
            window.name = theRequest.name;
            if (theRequest.index) {
                data = outData(allData, theRequest.index);
            }
            // console.log(theRequest);
            data_list = data[theRequest.id].list.filter(item => item.name == theRequest.name)[0]
            // console.log(data_list);
        } else {
            data = outData(allData, 0);
        }
        // console.log(data);
        // 初始化页面内容
        initializeContent();

    } catch (error) {
        console.error('Error loading JSON:', error);
    }
}

//问卷题目
function initializeContent() {
    let oform = document.querySelector('.submit-form');
    let oQuestion = `        <div class="subimt_header">
                                <h1>${data_list.text}</h1>
                            </div>
                            <div class="info"></div>
                            <img src="../images/${data_list.img}" alt="${data_list.name}" loading="lazy">
                            <div class="btnfrom">Scroll To Start Quiz</div>`
    for (let i = 0; i < data_list.questions.length; i++) {
        if (i == 1 || i == 3 || i == 5) {
            oQuestion += ` <div class="question_item adver"></div>`
        }
        let oPtions = ``
        for (let j = 0; j < data_list.questions[i].options.length; j++) {
            oPtions +=
                `
        <div class="option-item">
                                        <input type="radio" id="q${i + 1}_${j + 1}" name="question${i + 1}" value="${j + 1}">
                                        <label for="q${i + 1}_${j + 1}">${data_list.questions[i].options[j]}</label>
                                    </div>
        `
        }
        if (data_list.questions[i].img) {
            oQuestion +=
                `
    <div class="question-group ${i === 0 ? 'active' : 'disabled'}" id="question${i + 1}">
                                <div class="num_question">${data_list.questions[i].id}/${data_list.questions.length}</div>
                                <img src="../images/${data_list.questions[i].img}" alt="" class="question-image" loading="lazy">
                                <div class="question-title">${data_list.questions[i].text}</div>
                                <div class="options-group">
                                    ${oPtions}
                                </div>
                                </div>
    `
        } else {
            oQuestion +=
                `
    <div class="question-group ${i === 0 ? 'active' : 'disabled'}" id="question${i + 1}">
                                <div class="num_question">${data_list.questions[i].id}/${data_list.questions.length}</div>
                                <div class="question-title" style="margin-left:35px;">${data_list.questions[i].text}</div>
                                <div class="options-group">
                                    ${oPtions}
                                </div>
                                </div>
    `
        }
    }
    oQuestion += '  <button type="submit" class="submit-btn" disabled>Submit</button>'
    oform.innerHTML = oQuestion

    //next列表
    let oBNextList = data[theRequest.id].list.filter(item => item.name !== theRequest.name)
    let oBNextUl = document.querySelector('.next_list ul');
    let oRNextList = data[0].list.filter(item => item.name !== theRequest.name)
    let oRNextUl = document.querySelector('.most_list ul');
    createNextList(oBNextList, oBNextUl, 'next')
    createNextList(oRNextList, oRNextUl, 'most')
    function createNextList(oNextList, oNextUl, type) {
        let oNextLi = ''
        for (let i = 0; i < 6; i++) {
            oNextLi +=
                `<li class="${type}_list_item">
                                <div class="item_img">
                                    <img src="../images/${oNextList[i].img}" alt="${oNextList[i].name}">
                                </div>
                                <div class="item_title">${oNextList[i].text}</div>
                            </li>
    `
        }
        oNextUl.innerHTML = oNextLi
        let allLi = oNextUl.querySelectorAll("li")
        for (let i = 0; i < allLi.length; i++) {
            allLi[i].addEventListener('click', (e) => {
                e.preventDefault();
                // if (type === 'next') {
                //     gotoFrom(theRequest.id, oNextList[i].name)
                // } else {
                gotoFrom(0, oNextList[i].name)
                // }
            })
        }
    }

    // 在内容渲染完成后添加事件监听
    initializeFormEvents();
}

// 将所有表单相关的事件处理封装到单独的函数中
function initializeFormEvents() {
    const form = document.getElementById('questionForm');
    const questions = document.querySelectorAll('.question-group');
    const submitBtn = document.querySelector('.submit-btn');
    const submitHeader = document.querySelector('.subimt_header');
    const btnFrom = document.querySelector('.btnfrom');

    if (!form || !submitHeader || !btnFrom) {
        console.error('Required elements not found');
        return;
    }

    // 滚动到第一个问题的函数
    function scrollToFirstQuestion() {
        const firstQuestion = document.getElementById('question1');
        if (firstQuestion) {
            firstQuestion.scrollIntoView({
                behavior: 'smooth',
                block: 'center'
            });
        }
    }

    // 为标题和按钮添加点击事件监听器
    submitHeader.addEventListener('click', scrollToFirstQuestion);
    btnFrom.addEventListener('click', scrollToFirstQuestion);

    // 监听每个问题的radio按钮变化
    questions.forEach((question, index) => {
        const radios = question.querySelectorAll('input[type="radio"]');
        const optionItems = question.querySelectorAll('.option-item');

        radios.forEach((radio, optionIndex) => {
            radio.addEventListener('change', () => {
                // 移除当前问题所有选项的选中样式
                optionItems.forEach(item => {
                    item.classList.remove('selected');
                });

                // 为选中的选项添加样式
                const selectedOption = optionItems[optionIndex];
                selectedOption.classList.add('selected');

                handleQuestionAnswer(question, index);
            });
        });

        // 为选项添加点击事件
        optionItems.forEach((item, optionIndex) => {
            item.addEventListener('click', () => {
                const radio = radios[optionIndex];
                if (radio) {
                    radio.checked = true;
                    // 触发change事件
                    const event = new Event('change');
                    radio.dispatchEvent(event);
                }
            });
        });
    });

    // 处理问题回答
    function handleQuestionAnswer(question, index) {
        // 标记当前问题为已完成
        question.classList.remove('active');
        question.classList.add('completed');

        // 如果不是最后一题，解锁并激活下一题
        if (index < questions.length - 1) {
            questions.forEach(q => q.classList.remove('active'));
            questions[index + 1].classList.remove('disabled');
            questions[index + 1].classList.add('active');

            // 平滑滚动到下一题
            questions[index + 1].scrollIntoView({
                behavior: 'smooth',
                block: 'center'
            });
        } else {
            // 如果是最后一题，滚动到 next_list
            const nextList = document.querySelector('.next_list');
            if (nextList) {
                setTimeout(() => {
                    nextList.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }, 500);
            }
        }

        // 检查是否所有题目都已答完
        checkAllCompleted();
    }

    // 检查是否所有题目都已完成
    function checkAllCompleted() {
        const allCompleted = Array.from(questions).every(question => {
            const radios = question.querySelectorAll('input[type="radio"]');
            return Array.from(radios).some(radio => radio.checked);
        });

        if (submitBtn) {
            submitBtn.disabled = !allCompleted;
        }
    }

    // 表单提交事件处理
    if (form) {
        form.addEventListener('submit', handleFormSubmit);
    }

    // 允许点击已完成的题目重新作答
    questions.forEach((question, index) => {
        question.addEventListener('click', () => {
            const radios = question.querySelectorAll('input[type="radio"]');
            const isCompleted = Array.from(radios).some(radio => radio.checked);

            // 如果是第一题或已完成的题目，允许重新作答
            if (index === 0 || isCompleted) {
                questions.forEach(q => q.classList.remove('active'));
                question.classList.add('active');
                question.classList.remove('disabled');
            }
        });
    });
}

// 处理表单提交
function handleFormSubmit(e) {
    e.preventDefault();

    const questions = document.querySelectorAll('.question-group');
    const answers = {};

    questions.forEach((question, index) => {
        const questionNumber = index + 1;
        const selectedRadio = question.querySelector('input[type="radio"]:checked');
        if (selectedRadio) {
            const selectedLabel = question.querySelector(`label[for="${selectedRadio.id}"]`);
            const questionTitle = question.querySelector('.question-title');

            answers[`问题${questionNumber}`] = {
                question: questionTitle ? questionTitle.textContent.trim() : '',
                answer: selectedLabel ? selectedLabel.textContent.trim() : '',
                value: selectedRadio.value
            };
        }
    });

    console.log('问卷答案：', answers);

    // 显示结果
    showResults(this);
}
function gotoFrom(id, item) {
    const index = new URLSearchParams(location.search).get('index') || 0;
    location.href = `../pages/from.html?id=${id}&name=${item}&index=${index}`;
}
// 显示结果
function showResults(form) {
    const resultHtml = `
        <div class="retest-container">
            <img src="../images/${data_list.img}" alt="${data_list.name}">
            <h2 style="text-align:left;">Sleepy student</h2>
            <p style="text-align:left;">You're always daydreaming in class and struggle to keep your eyes open. While you might not always pay attention, you have great potential when you focus.</p>
            <button type="button" class="retest-btn" onclick="location.reload()">Test Again</button>
        </div>`;

    form.innerHTML = resultHtml;

    // 滚动到结果区域
    const resultContainer = form.querySelector('.retest-container');
    if (resultContainer) {
        resultContainer.scrollIntoView({
            behavior: 'smooth',
            block: 'center'
        });
    }
}
